const { request } = require('../../../utils/request');

Page({
  data: {
    phone: '',
    username: '',
    nickname: '',
    password: '',
    isLoading: false,
    showPassword: false, // 👈 控制密码可见性
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },
  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },
  onNicknameInput(e) {
    this.setData({ nickname: e.detail.value });
  },
  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },
  toggleShowPassword() {
    this.setData({ showPassword: !this.data.showPassword });
  },

  async register() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });

    try {
      const res = await request({
        url: '/user/register',
        method: 'POST',
        data: {
          phone: this.data.phone,
          username: this.data.username,
          nickname: this.data.nickname,
          password: this.data.password,
        }
      });
      if (res.code === 2000) {
        wx.showToast({ title: '注册成功' });
        setTimeout(() => {
          wx.redirectTo({ url: '/pages/login/login' });
        }, 500);
      } else {
        wx.showToast({ title: res.message || '注册失败', icon: 'none' });
      }
    } catch (err) {
      wx.showToast({ title: '请求失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  goBackLogin() {
    wx.redirectTo({
      url: '/page/component/login/index',
    });
  }
});
